package furniture.design.popup.actions;

import java.io.IOException;

import org.eclipse.core.resources.IFile;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

public class FurnitureAction implements IObjectActionDelegate {
	
	/**
	 * Constructor for Action1.
	 */
	public FurnitureAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		
	}

	ISelection s = null;
	
	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {

		
		if (s instanceof IStructuredSelection){
			Object o = ((IStructuredSelection) s).getFirstElement();
			if (o instanceof IFile){
				
				IFile src = (IFile)o;
				URI srcuri = URI.createPlatformResourceURI(src.getFullPath().toString(), true);
				URI outuri = srcuri.trimSegments(1).appendSegment(src.getName()+".furniture");
				
				ResourceSet rs = new ResourceSetImpl();
				Resource rsrc = rs.getResource(srcuri, true);
				Resource out = rs.createResource(outuri);
				
				for(EObject e : rsrc.getContents()){
					out.getContents().add(EcoreUtil.copy(e));
				}
				try {
					out.save(null);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		s = selection;
	}

}
